<?php

namespace App\Jobs\QiPao\Gift;

use App\Exceptions\BasicException;
use App\Jobs\Job;
use App\Models\MainDB\UserData;
use App\Services\Tools\IdempotentConsume;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class GiftWallJob extends Job
{
    protected $data;
    const jobName = 'GiftWallJob';

    public function __construct($data)
    {
        $this->data = $data;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        if(env('APP_ENV') != 'production'){
            Log::error('giftWallJob:' . json_encode(['time' => getMillisecond(), 'data' => $this->data]));
        }
        try {
            //获取上一次收到的礼物数量
//            $lastNumber = app('model_user_gift_wall')->where('user_id', $this->data['gift_user'])->where('gift_id', $this->data['gift_id'])->value('number');
            $idempotentConsumeServer =  new IdempotentConsume();
            $data = $this->data;
            $uk = $data['id']??'';
            if($idempotentConsumeServer->checkIdempotentRedisKey(self::jobName,$uk)){
                //更新用户礼物墙
//                app('repo_gift')->addUserGiftWall($this->data); // 原先礼物墙
                if($this->data->type == 0 || $this->data->type == 5){
                    DB::beginTransaction();
                    try{
                        $userId = $this->data['user_id'];
                        $giftUserId = $this->data['gift_user'];
                        // 锁住用户(期间更新用户信息需等待
//                        UserData::query()->whereIn('user_id', [$userId, $giftUserId])->lockForUpdate()->get();
                        app('repo_gift')->addUserGetGiftWall($this->data); // v35 新版礼物墙
                        app('repo_gift')->addUserGiveGiftWall($this->data); // v35 新版礼物墙
                        DB::commit();
                    }catch (\Exception $e){
                        DB::rollBack();
                        throw new BasicException($e->getCode(),  $e->getMessage());
                    }

                }

                //更新礼物墙积分
                //            app('repo_gift_wall')->updateUserGiftWallRank($this->data['gift_user'],$this->data['gift_id'],$lastNumber ? $lastNumber : 0);
                // $this->updateUserGiftWallRank($this->data['gift_user']); // 没用到
            }

        } catch (\Exception $exception) {
            $idempotentConsumeServer->deleteIdempotentRedisKey(self::jobName,$data['id']);
            Log::error('GiftWallJob:'.$exception->getMessage());
        }
    }

   /* public function fail($exception=null )
    {
        Log::error('ConnectionJob:'.$exception->getMessage());
    }*/

    public function updateUserGiftWallRank($userId)
    {
        $redisRankKey = [
            23 => 'user:gift_wall_rank:normal',
            24 => 'user:gift_wall_rank:special',
            25 => 'user:gift_wall_rank:activity'
        ];
        $redisRecordKey = [
            23 => 'user:gift_wall_record:normal:',
            24 => 'user:gift_wall_record:special:',
            25 => 'user:gift_wall_record:activity:'
        ];
        $frameList = app('model_gift_frame')->where('deleted', 0)->get()->toArray();
        $frameMap = array_column($frameList, null, 'id');
        unset($frameList);
        $redis = app('redis');
        $giftTypeList = app('model_gift_type')->select(['id', 'parent_id'])->get()->toArray();
        $giftTypeMap = $userScore = [];
        foreach ($giftTypeList as $value) {
            if (!isset($value['parent_id']) || !$value['parent_id']) {
                $giftTypeMap[$value['id']] = [];
                $userScore[$value['id']] = 0;
            }
        }
        foreach ($giftTypeList as $value) {
            if (isset($giftTypeMap[$value['parent_id']])) {
                $giftTypeMap[$value['parent_id']][] = $value['id'];
            }
        }

        $userGiftWallList = app('model_user_gift_wall')
            ->from('ln_user_gift_wall as base')
            ->join('ln_gift as g', 'base.gift_id', '=', 'g.id')
            ->where([
                'base.user_id' => $userId,
            ])
            ->select('base.gift_id','base.number','g.type','g.frame_id')
            ->get()->toArray();

        if (!empty($userGiftWallList)) {
            $temp = $userScore;
            foreach ($userGiftWallList as $v) {
                $frameDetail = $frameMap[$v['frame_id']] ?? [];
                if (empty($frameDetail)) {
                    continue;
                }
                $index = $score = 0;
                switch ($v['number']) {
                    case $v['number']>=$frameDetail['condition3']:
                        $score = $frameDetail['three_star_score']; break;
                    case $v['number']>=$frameDetail['condition2']:
                        $score = $frameDetail['two_star_score']; break;
                    case $v['number']>=$frameDetail['condition1']:
                        $score = $frameDetail['one_star_score']; break;
                    default:
                        $score = $frameDetail['default_score'];
                }
                foreach ($giftTypeMap as $kk => $vv) {
                    if (in_array($v['type'], $vv)) {
                        $index = $kk;
                    }
                }
                if ($index) {
                    $temp[$index] += $score;
                }
            }
            // 排行榜处理
            foreach ($temp as $kkk => $vvv) {
                if (isset($redisRankKey[$kkk])) $redis->zincrby($redisRankKey[$kkk], $vvv, $userId);
                if (isset($redisRecordKey[$kkk])) $redis->set($redisRecordKey[$kkk] . $userId, $vvv);
            }
            $redis->zincrby('user:gift_wall_rank:all', array_sum($temp), $userId);
        }
    }
}
